package com.shujia.flink.window;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

public class Demo02SessionWindow {
    public static void main(String[] args) throws Exception {
        /*  2、基于会话的窗口
         * 基于事件时间：EventTimeSessionWindows
         * 基于处理时间：ProcessingTimeSessionWindows
         */
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStream<String> wordDS = env.socketTextStream("master", 8888);

        // 基于处理时间：ProcessingTimeSessionWindows
//        wordDS.map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT))
//                .keyBy(kv->kv.f0)
//                .window(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
//                .sum(1)
//                .print();

        // 基于事件时间：EventTimeSessionWindows
        // 指定事件时间以及水位线
        DataStream<Tuple2<String, Long>> assignDS = wordDS.map(line -> {
                    String[] split = line.split(",");
                    String word = split[0];
                    long ts = Long.parseLong(split[1]);
                    return Tuple2.of(word, ts);
                }, Types.TUPLE(Types.STRING, Types.LONG))
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<Tuple2<String, Long>>forMonotonousTimestamps()
                        .withTimestampAssigner((kv, ts) -> kv.f1)
                );

        assignDS.map(word -> Tuple2.of(word.f0, 1), Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(kv->kv.f0)
                .window(EventTimeSessionWindows.withGap(Time.seconds(5)))
                .sum(1)
                .print();

        env.execute();

    }
}
